const Parse = require('parse/node')
const appInfo = require('./appinfo')

Parse.Cloud.define('wxLogin', function (req, res) {
  _wxLogin(req.params.code)
    .then(data => res.success(data))
    .catch(err => res.error(err))
})

function _wxLogin (code) {
  return new Promise((resolve, reject) => {
    Parse.Cloud.httpRequest({
      url: `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appInfo.AppID}&secret=${appInfo.AppSecret}&code=${code}&grant_type=authorization_code`
    }).then(function (httpResponse) {
      var data = JSON.parse(httpResponse.text)
      resolve(data)
    }, function (httpResponse) {
      reject('Request failed with response code ' + httpResponse.status)
    })
  })
}
